package com.fary.web.method.annotation;

import com.fary.beans.factory.config.BeanExpressionContext;
import com.fary.beans.factory.config.BeanExpressionResolver;
import com.fary.beans.factory.config.ConfigurableBeanFactory;
import com.fary.core.MethodParameter;
import com.fary.core.SpringException;
import com.fary.web.bind.WebDataBinder;
import com.fary.web.bind.annotation.ValueConstants;
import com.fary.web.bind.support.WebDataBinderFactory;
import com.fary.web.context.request.NativeWebRequest;
import com.fary.web.context.request.RequestScope;
import com.fary.web.method.support.HandlerMethodArgumentResolver;
import com.fary.web.method.support.ModelAndViewContainer;
import jdk.internal.jline.internal.Nullable;

import javax.servlet.ServletException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private final ConfigurableBeanFactory configurableBeanFactory;

    private final BeanExpressionContext expressionContext;

    private final Map<MethodParameter, NamedValueInfo> namedValueInfoCache = new ConcurrentHashMap<>(256);


    public AbstractNamedValueMethodArgumentResolver() {
        this.configurableBeanFactory = null;
        this.expressionContext = null;
    }

    /**
     * Create a new {@link AbstractNamedValueMethodArgumentResolver} instance.
     *
     * @param beanFactory a bean factory to use for resolving ${...} placeholder
     *                    and #{...} SpEL expressions in default values, or {@code null} if default
     *                    values are not expected to contain expressions
     */
    public AbstractNamedValueMethodArgumentResolver(ConfigurableBeanFactory beanFactory) {
        this.configurableBeanFactory = beanFactory;
        this.expressionContext = (beanFactory != null ? new BeanExpressionContext(beanFactory, new RequestScope()) : null);
    }


    @Override
    public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        // 1.NamedValueInfo对象包含了name,required,defaultValue三个信息
        NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
        // 获取MethodParameter对象,该对象封装了方法参数的规范
        MethodParameter nestedParameter = parameter.nestedIfOptional();

        // 2.解析参数名,包括占位符和表达式等
        Object resolvedName = resolveStringValue(namedValueInfo.name);
        if (resolvedName == null) {
            throw new IllegalArgumentException("Specified name must not resolve to null: [" + namedValueInfo.name + "]");
        }

        // 3.将给定的参数类型和值名称解析为参数值。
        Object arg = resolveName(resolvedName.toString(), nestedParameter, webRequest);
        // 如果未能正常解析
        /**
         * 如
         * 方法参数 : @RequestParam(name = "name") String name
         * 请求路径参数后缀 : sayHello?1212
         *
         * 未指定参数名称,则无法正常解析,接下来要判断NamedValueInfo属性值,并作出后续处理
         */
        if (arg == null) {
            // 如果默认值不为空,则
            if (namedValueInfo.defaultValue != null) {
                arg = resolveStringValue(namedValueInfo.defaultValue);
                // 指定了required属性且该参数不是为非不必须,则调动handleMissingValue方法处理缺失值,该方法一般会抛出异常
            } else if (namedValueInfo.required && !nestedParameter.isOptional()) {
                handleMissingValue(namedValueInfo.name, nestedParameter, webRequest);
            }
            // 最后处理将该参数值处理为null即可
            arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
        } else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
            arg = resolveStringValue(namedValueInfo.defaultValue);
        }

        if (binderFactory != null) {
            // 4.创建WebDataBinder实例
            WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
            try {
                // 5.尝试转换参数
                arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
            } catch (SpringException ex) {
                throw new SpringException(ex.getCause());
            }
        }

        handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);

        return arg;
    }

    /**
     * Obtain the named value for the given method parameter.
     */
    private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
        NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
        if (namedValueInfo == null) {
            namedValueInfo = createNamedValueInfo(parameter);
            namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
            this.namedValueInfoCache.put(parameter, namedValueInfo);
        }
        return namedValueInfo;
    }

    /**
     * Create the {@link NamedValueInfo} object for the given method parameter. Implementations typically
     * retrieve the method annotation by means of {@link MethodParameter#getParameterAnnotation(Class)}.
     *
     * @param parameter the method parameter
     * @return the named value information
     */
    protected abstract NamedValueInfo createNamedValueInfo(MethodParameter parameter);

    /**
     * Create a new NamedValueInfo based on the given NamedValueInfo with sanitized values.
     */
    private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
        String name = info.name;
        if (info.name.isEmpty()) {
            name = parameter.getParameterName();
            if (name == null) {
                throw new IllegalArgumentException(
                        "Name for argument type [" + parameter.getNestedParameterType().getName() +
                                "] not available, and parameter name information not found in class file either.");
            }
        }
        String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
        return new NamedValueInfo(name, info.required, defaultValue);
    }

    /**
     * Resolve the given annotation-specified value,
     * potentially containing placeholders and expressions.
     */
    @Nullable
    private Object resolveStringValue(String value) {
        if (this.configurableBeanFactory == null) {
            return value;
        }
        String placeholdersResolved = this.configurableBeanFactory.resolveEmbeddedValue(value);
        BeanExpressionResolver exprResolver = this.configurableBeanFactory.getBeanExpressionResolver();
        if (exprResolver == null || this.expressionContext == null) {
            return value;
        }
        return exprResolver.evaluate(placeholdersResolved, this.expressionContext);
    }

    /**
     * Resolve the given parameter type and value name into an argument value.
     *
     * @param name      the name of the value being resolved
     * @param parameter the method parameter to resolve to an argument value
     *                  (pre-nested in case of a {@link java.util.Optional} declaration)
     * @param request   the current request
     * @return the resolved argument (may be {@code null})
     * @throws Exception in case of errors
     */
    protected abstract Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception;

    /**
     * Invoked when a named value is required, but {@link #resolveName(String, MethodParameter, NativeWebRequest)}
     * returned {@code null} and there is no default value. Subclasses typically throw an exception in this case.
     *
     * @param name      the name for the value
     * @param parameter the method parameter
     * @param request   the current request
     * @since 4.3
     */
    protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        handleMissingValue(name, parameter);
    }

    /**
     * Invoked when a named value is required, but {@link #resolveName(String, MethodParameter, NativeWebRequest)}
     * returned {@code null} and there is no default value. Subclasses typically throw an exception in this case.
     *
     * @param name      the name for the value
     * @param parameter the method parameter
     */
    protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException {
        throw new SpringException("Missing argument '" + name + "' for method parameter of type " + parameter.getNestedParameterType().getSimpleName());
    }

    /**
     * A {@code null} results in a {@code false} value for {@code boolean}s or an exception for other primitives.
     */
    private Object handleNullValue(String name, Object value, Class<?> paramType) {
        if (value == null) {
            if (Boolean.TYPE.equals(paramType)) {
                return Boolean.FALSE;
            } else if (paramType.isPrimitive()) {
                throw new IllegalStateException("Optional " + paramType.getSimpleName() + " parameter '" + name +
                        "' is present but cannot be translated into a null value due to being declared as a " +
                        "primitive type. Consider declaring it as object wrapper for the corresponding primitive type.");
            }
        }
        return value;
    }

    /**
     * 值完全处理结束后，把处理好的值放进请求域，方便view里渲染时候使用~
     * 抽象父类的handleResolvedValue方法，只有它复写了~
     */
    protected void handleResolvedValue(Object arg, String name, MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) {
    }


    /**
     * Represents the information about a named value, including name, whether it's required and a default value.
     */
    protected static class NamedValueInfo {

        private final String name;

        private final boolean required;

        private final String defaultValue;

        public NamedValueInfo(String name, boolean required, String defaultValue) {
            this.name = name;
            this.required = required;
            this.defaultValue = defaultValue;
        }
    }

}